package com.example.testexfatwrite;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.Fatwrite.BuildConfig;
import com.example.Fatwrite.R;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import me.jahnen.libaums.core.UsbMassStorageDevice;
import me.jahnen.libaums.core.fs.FileSystem;
import me.jahnen.libaums.core.fs.UsbFile;
import me.jahnen.libaums.core.fs.UsbFileStreamFactory;
import me.jahnen.libaums.core.partition.Partition;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    /** * Build.MANUFACTURER */
    private static final String MANUFACTURER_HUAWEI = "Huawei";//华为
    private static final String MANUFACTURER_MEIZU = "Meizu";//魅族
    private static final String MANUFACTURER_XIAOMI = "Xiaomi";//小米
    private static final String MANUFACTURER_SONY = "Sony";//索尼
    private static final String MANUFACTURER_OPPO = "OPPO";
    private static final String MANUFACTURER_LG = "LG";
    private static final String MANUFACTURER_VIVO = "vivo";
    private static final String MANUFACTURER_SAMSUNG = "samsung";//三星
    private static final String MANUFACTURER_LETV = "Letv";//乐视
    private static final String MANUFACTURER_ZTE = "ZTE";//中兴
    private static final String MANUFACTURER_YULONG = "YuLong";//酷派
    private static final String MANUFACTURER_LENOVO = "LENOVO";//联想

    private static final String ACTION_USB_PERMISSION = "com.lenovo.exfat.USB_PERMISSION";
    private static final String KEY_MIUI_VERSION_CODE = "KEY_MIUI_VERSION_CODE";
    private static final String KEY_MIUI_VERSION_NAME = "KEY_MIUI_VERSION_NAME";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "KEY_MIUI_INTERNAL_STORAGE";
    private UsbManager mUsbManager;
    private PendingIntent mPermissionIntent;



    private EditText Sample_text;

    private TextView showText;
    private Button buttonPanel;
    private Button buttonPanel1;
    private Button buttonPanel2;
    private Button buttonPanel3;

    private Button loadImage;

    private ImageView imageView;

    private Button loadUsb;
    private ByteBuffer tempBuffer;
    private int MY_PERMISSION_REQUEST_CODE = 0;
    // Used to load the 'testexfatwrite' library on application startup.

    UsbMassStorageDevice storageDevice;
    static {
        System.loadLibrary("testexfatwrite");
    }

//    private ActivityMainBinding binding;

    // 这里为了适配小米手机所以需要处理一下权限
    /** * 检测权限 * * @return true 所需权限全部授取 false 存在未授权的权限 */
    public boolean isAllGranted() {
        /** * 第 1 步: 检查是否有相应的权限 */
        boolean isAllGranted = checkPermissionAllGranted(
                new String[]{
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }
        );
        return isAllGranted;
    }
    /** * 检查是否拥有指定的所有权限 */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }



// 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
    private void requestPermisionsAll(){
        ActivityCompat.requestPermissions(
                this,
                new String[]{
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                },
                MY_PERMISSION_REQUEST_CODE
        );
    }


    //  所有权限授取之后的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) {
                // 如果所有的权限都授予了, 跳转到主页
              //  gotoHomeActivity();
                Toast.makeText(this,"全部授权通过,可以正常使用",Toast.LENGTH_LONG).show();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
             //   openAppDetails();
                Toast.makeText(this,"没有全部授权，需要到授权页面授权",Toast.LENGTH_LONG).show();
                boolean miuipermision =   initMiuiPermission();
                if (miuipermision == false){
                    GoToSetting(this);
                }
            }
        }
    }

    //  判断是否是小米系统
    /** * 检查手机是否是miui系统 * * @return */
    public boolean isMIUI() {
        String device = Build.MANUFACTURER;
        System.out.println("Build.MANUFACTURER = " + device);
        if (device.equals("Xiaomi")) {
            System.out.println("this is a xiaomi device");
            Properties prop = new Properties();
            try {
                prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                    || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                    || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
        } else {
            return false;
        }
    }

    /** * 判断小米MIUI系统中授权管理中对应的权限授取 * * @return false 存在核心的未收取的权限 true 核心权限已经全部授权 */
    public boolean initMiuiPermission() {
        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int locationOp = appOpsManager.checkOp(AppOpsManager.OPSTR_FINE_LOCATION, Binder.getCallingUid(), getPackageName());
        if (locationOp == AppOpsManager.MODE_IGNORED) {
            return false;
        }
        int cameraOp = appOpsManager.checkOp(AppOpsManager.OPSTR_CAMERA, Binder.getCallingUid(), getPackageName());
        if (cameraOp == AppOpsManager.MODE_IGNORED) {
            return false;
        }
        int phoneStateOp = appOpsManager.checkOp(AppOpsManager.OPSTR_READ_PHONE_STATE, Binder.getCallingUid(), getPackageName());
        if (phoneStateOp == AppOpsManager.MODE_IGNORED) {
            return false;
        }
        int readSDOp = appOpsManager.checkOp(AppOpsManager.OPSTR_READ_EXTERNAL_STORAGE, Binder.getCallingUid(), getPackageName());
        if (readSDOp == AppOpsManager.MODE_IGNORED) {
            return false;
        }
        int writeSDOp = appOpsManager.checkOp(AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE, Binder.getCallingUid(), getPackageName());
        if (writeSDOp == AppOpsManager.MODE_IGNORED) {
            return false;
        }
        return true;
    }

    public static void Xiaomi(Activity activity) {
        // 只兼容miui v5/v6 的应用权限设置页面，否则的话跳转应用设置页面（权限设置上一级页面）
        String miuiVersion = getMiuiVersion();
        Intent intent = null;
        if ("V5".equals(miuiVersion)) {
            Uri packageURI = Uri.parse("package:" + activity.getApplicationInfo().packageName);
            intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
        } else if ("V6".equals(miuiVersion) || "V7".equals(miuiVersion)) {
            intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
        } else if ("V8".equals(miuiVersion)) {
            intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
        } else {
        }
        if (null != intent)
            activity.startActivity(intent);
    }
    public static void Huawei(Activity activity) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    public static void Meizu(Activity activity) {
        Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        activity.startActivity(intent);
    }

    public static void Sony(Activity activity) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    public static void OPPO(Activity activity) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.color.safecenter", "com.color.safecenter.permission.PermissionManagerActivity");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    public static void LG(Activity activity) {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    public static void Letv(Activity activity) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.PermissionAndApps");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    /** * 只能打开到自带安全软件 * * @param activity */
    public static void _360(Activity activity) {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
        ComponentName comp = new ComponentName("com.qihoo360.mobilesafe", "com.qihoo360.mobilesafe.ui.index.AppEnterActivity");
        intent.setComponent(comp);
        activity.startActivity(intent);
    }
    /** * 应用信息界面 * * @param activity */
    public static void ApplicationInfo(Activity activity) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
        }
        activity.startActivity(localIntent);
    }
    /** * 系统设置界面 * * @param activity */
    public static void SystemConfig(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        activity.startActivity(intent);
    }
    public static String getMiuiVersion() {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop ro.miui.ui.version.name");
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return line;
    }
    /** * 此函数可以自己定义 * * @param activity */
    public static void GoToSetting(Activity activity) {
        switch (Build.MANUFACTURER) {
            case MANUFACTURER_HUAWEI:
                Huawei(activity);
                break;
            case MANUFACTURER_MEIZU:
                Meizu(activity);
                break;
            case MANUFACTURER_XIAOMI:
                Xiaomi(activity);
                break;
            case MANUFACTURER_SONY:
                Sony(activity);
                break;
            case MANUFACTURER_OPPO:
                OPPO(activity);
                break;
            case MANUFACTURER_LG:
                LG(activity);
                break;
            case MANUFACTURER_LETV:
                Letv(activity);
                break;
            default:
                ApplicationInfo(activity);
              //  Log.e("goToSetting", "目前暂不支持此系统");
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(R.layout.activity_main);

        init();

        boolean isallgrand = isAllGranted();

        if (isallgrand == false){
            requestPermisionsAll();
        }
        if (isMIUI()) {
            Toast.makeText(this, "是小米手机", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(this, "不是小米手机", Toast.LENGTH_LONG).show();
        }
        boolean miuipermision =   initMiuiPermission();
        if (miuipermision == false){
            GoToSetting(this);
        }

        ByteBuffer bf =  ByteBuffer.allocate(1024);
        bf.order(ByteOrder.LITTLE_ENDIAN);
        for (int i = 0;i<1024;i++){
                bf.put((byte)i);
        }
        bf.flip();
        ByteBuffer buffer = ByteBuffer.allocate(100);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        byte[] testbyte = new byte[100];
        bf.get(testbyte,0,100);
        buffer.put(testbyte);
        int len =  bf.remaining();
        bf.position(2);
        ByteBuffer tempbuffer = ByteBuffer.allocate(10);
        for (int i = 0;i < 10;i ++){
            tempbuffer.put((byte)(i*10));
        }
        tempbuffer.flip();
        bf.put(tempbuffer);

        bf.clear();

        for (int i = 0;i < 10; i ++){
            byte temp = bf.get();
        }


        // Example of a call to a native method
        Sample_text = findViewById(R.id.sample_text);
        showText = findViewById(R.id.showText);

        showText.setText("adfjalsdfkjl");

        loadUsb = findViewById(R.id.loadusb);
        buttonPanel = findViewById(R.id.buttonPanel);
        buttonPanel1 = findViewById(R.id.buttonPanel1);
        buttonPanel2 = findViewById(R.id.buttonPanel2);
        buttonPanel3 = findViewById(R.id.buttonPanel3);

        loadImage = findViewById(R.id.showimage);
        imageView = findViewById(R.id.imageView);


        buttonPanel.setOnClickListener(this);
        buttonPanel1.setOnClickListener(this);
        buttonPanel2.setOnClickListener(this);
        buttonPanel3.setOnClickListener(this);
        loadUsb.setOnClickListener(this);

        loadImage.setOnClickListener(this);
      //  imageView.setOnClickListener(this);

    }
    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (action == null)
                return;
            switch (action) {
                case ACTION_USB_PERMISSION://用户授权广播
                    synchronized (this) {
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允许权限申请
                            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                                if (device != null) {
                                    try {
                                        setupDevice();
                                    } catch (IOException e) {
                                        Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } else {

                        }
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://USB设备插入广播
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (device != null) {
                        discoverDevice();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://USB设备拔出广播

                    break;
            }

        }
    };
    private void init(){

        //USB管理器
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        //注册广播,监听USB插入和拔出
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(usbReceiver, intentFilter);
        //读写权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE}, 111);
        }
    }
    public void discoverDevice(){

    }

    public void logShow(String msg){
//        Log.e(TAG,msg);
        Toast.makeText(this,msg,Toast.LENGTH_LONG).show();

    }
    private void test() {
//        Toast.makeText(this,"开始测试",Toast.LENGTH_LONG).show();
        try {
            UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
            if (storageDevices.length <= 0){
                logShow("当前usb设备为空");
            }else{

            }
            for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
                // 申请USB权限
                if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
                    mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
                //    Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
                    break;
                }
                // 初始化
//                storageDevice.init();
//                // 获取分区
//                List<Partition> partitions = storageDevice.getPartitions();
//                if (partitions.size() == 0) {
//                    logShow("错误: 读取分区失败");
//                    return;
//                }
//                // 仅使用第一分区
//                FileSystem fileSystem = partitions.get(0).getFileSystem();
//                logShow("Volume Label: " + fileSystem.getVolumeLabel());
//                logShow("Capacity: " + fSize(fileSystem.getCapacity()));
//                logShow("Occupied Space: " + fSize(fileSystem.getOccupiedSpace()));
//                logShow("Free Space: " + fSize(fileSystem.getFreeSpace()));
//                logShow("Chunk size: " + fSize(fileSystem.getChunkSize()));
//
//                UsbFile root = fileSystem.getRootDirectory();
//                UsbFile[] files = root.listFiles();
//                UsbFile newFile = null;
//                for (UsbFile file : files)
//                    logShow("文件: " + file.getName());
//
//                // 新建文件
//                {
//                }
//                newFile = root.createFile("hello_" + System.currentTimeMillis() + ".txt");
//                logShow("新建文件: " + newFile.getName());
//
//                // 写文件
//                // OutputStream os = new UsbFileOutputStream(newFile);
//                OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
//                os.write(("hi_" + System.currentTimeMillis()).getBytes());
//                os.close();
//                logShow("写文件: " + newFile.getName());
//
//                // 读文件
//                // InputStream is = new UsbFileInputStream(newFile);
//                InputStream is = UsbFileStreamFactory.createBufferedInputStream(newFile, fileSystem);
//                byte[] buffer = new byte[fileSystem.getChunkSize()];
//                int len;
//                File sdFile = new File("/sdcard/111");
//                sdFile.mkdirs();
//                FileOutputStream sdOut = new FileOutputStream(sdFile.getAbsolutePath() + "/" + newFile.getName());
//                while ((len = is.read(buffer)) != -1) {
//                    sdOut.write(buffer, 0, len);
//                }
//                is.close();
//                sdOut.close();
//                logShow("读文件: " + newFile.getName() + " ->复制到/sdcard/111/");
//
//                storageDevice.close();
            }
        } catch (Exception e) {
            logShow("错误: " + e);
        }
    }

    public static String fSize(long sizeInByte) {
        if (sizeInByte < 1024)
            return String.format("%s", sizeInByte);
        else if (sizeInByte < 1024 * 1024)
            return String.format(Locale.CANADA, "%.2fKB", sizeInByte / 1024.);
        else if (sizeInByte < 1024 * 1024 * 1024)
            return String.format(Locale.CANADA, "%.2fMB", sizeInByte / 1024. / 1024);
        else
            return String.format(Locale.CANADA, "%.2fGB", sizeInByte / 1024. / 1024 / 1024);
    }
    private void setupDevice() throws IOException {

//        Toast.makeText(this,"开始测试",Toast.LENGTH_LONG).show();
        try {
            UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
            if (storageDevices.length <= 0){
                logShow("当前usb设备为空");
            }
            for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
                // 申请USB权限
                if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
                    mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                    Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
                    break;
                }
                // 初始化
                storageDevice.init();
                this.storageDevice = storageDevice;
                logShow("设备挂载成功");
            }
        } catch (Exception e) {
            logShow("错误: " + e);
        }
//        try {
//        // 获取设备
//        massStorageDevice = UsbMassStorageDevice.getMassStorageDevices(this);
//        // 建立连接
//
//        UsbCommunicationInfo usbCommunicationInfo = massStorageDevice.createUsbCommunication();
//     //   Toast.makeText(this,"usbCommenutionInfo: " + usbCommunicationInfo.toString(),Toast.LENGTH_LONG).show();
//        // 创建文件系统
//
//     //   Log.i(TAG,"3. 开始创建文件系统");
//        ScsiBlockDevice blockDevice = BlockDeviceDriverFactory.createBlockDevice(usbCommunicationInfo);
//      //  ByteBlockDevice byteBlockDevice = new ByteBlockDevice(blockDevice,0);
//      //   Toast.makeText(this,"blockDevice: " + blockDevice.toString(),Toast.LENGTH_LONG).show();
//        fs = (ExFatFileSystem) FileSystemFactory.createFileSystem(null,blockDevice);
//
//       // fs.rootParser.parseLabel();
//      //  fs.rootParser.parseFileName();
//       // fs.rootParser.parseStreamExtension();
//
//            Toast.makeText(this,"文件系统构建完成",Toast.LENGTH_LONG).show();
//       runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Sample_text.setText("文件系统构建完成!");
//            }
//        });
//        }catch (IOException e){
//            throw e;
//        }
        //9. test find read delete file

        //fs.testExist();
     //  fs.testListFile();
        //fs.testFindFile();
        //fs.testReadFile();
        //fs.testDeleteFile();
        //fs.testCreateFile();
        //fs.testMkdir();
        //fs.testWriteFile();
    }

    @Override
    public void onClick(View var1){

        if (var1 == loadImage){
            try {
//                UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
//                if (storageDevices.length <= 0){
//                  //  logShow("当前usb设备为空");
//                }
//                for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
//                    // 申请USB权限
//                    if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
//                        mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                     //   Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
//                        break;
//                    }
//                    // 初始化
//                    storageDevice.init();
                // 获取分区
                List<Partition> partitions = this.storageDevice.getPartitions();
                if (partitions.size() == 0) {
                    logShow("错误: 读取分区失败");
                    return;
                }
                // 仅使用第一分区
                FileSystem fileSystem = partitions.get(0).getFileSystem();


                UsbFile root = fileSystem.getRootDirectory();
                UsbFile[] files = root.listFiles();
                UsbFile newFile = null;
                for (UsbFile file : files) {
//                    if(file == null)continue;
                    if(file.isDirectory()){

                    }else{
                        if (file.getName().contains(".jpg")){

                            showText.setText("图片长度: " + file.getLength());
//                            return;


                            InputStream is = UsbFileStreamFactory.createBufferedInputStream(file, fileSystem);
                            byte[] buffer = new byte[(int)file.getLength()];
                            int len;
                            while ((len = is.read(buffer)) != -1) {

                            }
//
////                            ByteBuffer bf = ByteBuffer.allocate((int)file.getLength());
////                            file.read((int)file.getLength(),bf);
                            Bitmap bmp = BitmapFactory.decodeByteArray(buffer,0,(int)file.getLength());
                            imageView.setImageBitmap(bmp);

                            showText.setText("读取的图片是: " + file.getName() + "文件长度是: " + file.getLength());
//
                            return;
                        }
                    }


                }


            } catch (Exception e) {
                showText.setText("错误: " + e);
                logShow("错误: " + e);
            }


        }else if (var1 == loadUsb){
            test();

        }else if (var1 == buttonPanel){
            try {
//                UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
//                if (storageDevices.length <= 0){
//                  //  logShow("当前usb设备为空");
//                }
//                for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
//                    // 申请USB权限
//                    if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
//                        mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                     //   Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
//                        break;
//                    }
//                    // 初始化
//                    storageDevice.init();
                    // 获取分区
                    List<Partition> partitions = this.storageDevice.getPartitions();
                    if (partitions.size() == 0) {
                        logShow("错误: 读取分区失败");
                        return;
                    }
                    // 仅使用第一分区
                    FileSystem fileSystem = partitions.get(0).getFileSystem();


                    UsbFile root = fileSystem.getRootDirectory();
                    UsbFile[] files = root.listFiles();
                    UsbFile newFile = null;
                    String filestring = "读取到的文件总共有: " + files.length + "个\r\n";
                    logShow(filestring);
                    for (UsbFile file : files) {
//                        logShow("文件: " + file.getName());
                        if(file.isDirectory()){
                            String s = "目录: " + file.getName();
                            filestring += s;
                        }else{
                            String s = "文件名: " + file.getName() + "文件大小: " + file.getLength() + "字节 ";
                            filestring += s;
                        }


                    }

                    logShow(filestring);
                   showText.setText(filestring);
                    // 新建文件
                    {
                    }
//                    newFile = root.createFile("hello_" + System.currentTimeMillis() + ".txt");
//                    logShow("新建文件: " + newFile.getName());
//
//                    // 写文件
//                    // OutputStream os = new UsbFileOutputStream(newFile);
//                    OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
//                    os.write(("hi_" + System.currentTimeMillis()).getBytes());
//                    os.close();
//                    logShow("写文件: " + newFile.getName());
//
//                    // 读文件
//                    // InputStream is = new UsbFileInputStream(newFile);
//                    InputStream is = UsbFileStreamFactory.createBufferedInputStream(newFile, fileSystem);
//                    byte[] buffer = new byte[fileSystem.getChunkSize()];
//                    int len;
//                    File sdFile = new File("/sdcard/111");
//                    sdFile.mkdirs();
//                    FileOutputStream sdOut = new FileOutputStream(sdFile.getAbsolutePath() + "/" + newFile.getName());
//                    while ((len = is.read(buffer)) != -1) {
//                        sdOut.write(buffer, 0, len);
//                    }
//                    is.close();
//                    sdOut.close();
//                    logShow("读文件: " + newFile.getName() + " ->复制到/sdcard/111/");

//                    thisstorageDevice.close();
//                }
            } catch (Exception e) {
                logShow("错误: " + e);
            }



//            try {
//                ExFatFile file = (ExFatFile)fs.getRootDirectory();
//             //   file.
//                String[] s = file.list();
//                String result = "";
//                ByteBuffer tempbuffer = ByteBuffer.allocate(512);
//                tempbuffer.order(ByteOrder.LITTLE_ENDIAN);
//
//                UsbFile[] files = file.listFiles();
//                for(int i=0 ; i < files.length;i++){
//                    String name = files[i].getName();
//                    if (name.equals("a.txt")){
//                        UsbFile usbFile = files[i];
//                        ExFatFile exFatFile = (ExFatFile)usbFile;
//                        usbFile.read(0,tempbuffer);
//                        tempbuffer.flip();
//                        result += " getfileCluster: " + exFatFile.getfileCluster() + "文件件扇区: " + ExFatUtil.clusterToOffset(exFatFile.getfileCluster());
//                    }
//                }
//
//                for (String s1:s) {
//                    result += s1;
//                }
//
//              //  Sample_text.append(s[0]);
//                Sample_text.setText(result);
//                long free = fs.getFreeSpace();
//
//              //  List<ExFatFile> fatFile = (List<ExFatFile>) fs.getFatList();
//             //   ExFatFile firstFile = fatFile.get(0);
//             //   firstFile.createDirectory("testFile");
//
//            //    String[] filelist = firstFile.list();
//
//             //   Toast.makeText(this,"capcacity: " + tempbuffer.capacity() + " limit: " + tempbuffer.limit(),Toast.LENGTH_LONG).show();
//
//                byte[] bt = new byte[tempbuffer.capacity()];
//                tempbuffer.get(bt);
//                String temps = new String(bt);
//                result += "a.txt文件内容:" + temps;
//                Sample_text.setText(result);
//
//                Toast.makeText(this,"isDirectory" + file.isDirectory() + "s.size: " + s.length + result + " free: " + free + " getAbsolutePath: " + file.getAbsolutePath()  + " 盘符: " + fs.getVolumeLabel() + " filelist: ",Toast.LENGTH_LONG).show();
//            }catch (IOException e){
//                Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
//            }


        }else if (var1 == buttonPanel1){

            try {
//                UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
//                if (storageDevices.length <= 0){
//                   // logShow("当前usb设备为空");
//                }
//                for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
//                    // 申请USB权限
//                    if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
//                        mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                      //  Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
//                        break;
//                    }
//                    // 初始化
//                    storageDevice.init();
                    // 获取分区
                    List<Partition> partitions = this.storageDevice.getPartitions();
                    if (partitions.size() == 0) {
                        logShow("错误: 读取分区失败");
                        return;
                    }
                    // 仅使用第一分区
                    FileSystem fileSystem = partitions.get(0).getFileSystem();


                    UsbFile root = fileSystem.getRootDirectory();
                    UsbFile[] files = root.listFiles();
                    String filestring = "";

                    for (UsbFile file : files) {
                        if (file.getName().contentEquals("a.txt")){

                            InputStream is = UsbFileStreamFactory.createBufferedInputStream(file, fileSystem);
                            byte[] buffer = new byte[(int)file.getLength()];
                            int len;
                            while ((len = is.read(buffer)) != -1) {

                            }
                            String fileText = new String(buffer);
                            showText.setText("文件 a.txt 读取的内容是：" + fileText);

                            is.close();
                        }
                    }
                    // 新建文件
                    {
                    }
//                    newFile = root.createFile("hello_" + System.currentTimeMillis() + ".txt");
//                    logShow("新建文件: " + newFile.getName());
//
//                    // 写文件
//                    // OutputStream os = new UsbFileOutputStream(newFile);
//                    OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
//                    os.write(("hi_" + System.currentTimeMillis()).getBytes());
//                    os.close();
//                    logShow("写文件: " + newFile.getName());
//
//                    // 读文件
//                    // InputStream is = new UsbFileInputStream(newFile);
//                    InputStream is = UsbFileStreamFactory.createBufferedInputStream(newFile, fileSystem);
//                    byte[] buffer = new byte[fileSystem.getChunkSize()];
//                    int len;
//                    File sdFile = new File("/sdcard/111");
//                    sdFile.mkdirs();
//                    FileOutputStream sdOut = new FileOutputStream(sdFile.getAbsolutePath() + "/" + newFile.getName());
//                    while ((len = is.read(buffer)) != -1) {
//                        sdOut.write(buffer, 0, len);
//                    }
//                    is.close();
//                    sdOut.close();
//                    logShow("读文件: " + newFile.getName() + " ->复制到/sdcard/111/");

//                    this.storageDevice.close();
//                }
            } catch (Exception e) {
                logShow("错误: " + e);
            }



//            try {
//            //    ByteBuffer buffer = ByteBuffer.allocate(6);
//             //   buffer.putChar('a').putChar('b').putChar('c').rewind();
//
//
//                ExFatFile file = (ExFatFile)fs.getRootDirectory();
//               // file.createDirectory("abc");
//                ExFatFile  abctxtFile =   (ExFatFile) file.createFile("abc.txt",512);
//
//                ByteBuffer bf =  ByteBuffer.allocate(512);
//                bf.order(ByteOrder.LITTLE_ENDIAN);
//                for (int i = 0;i<512;i++){
//                    if (i<100){
//                        bf.put((byte)97);
//                    }else {
//                        bf.put((byte)0);
//                    }
//                }
//                bf.flip();
//                abctxtFile.write(0,bf);
//                Toast.makeText(this,"写入成功",Toast.LENGTH_LONG).show();
//               /* UsbFile[] files = file.listFiles();
//                for(int i=0 ; i < files.length;i++){
//                    String name = files[i].getName();
//                    if (name.equals("a.txt")){
//                        UsbFile usbFile = files[i];
//                        ExFatFile exFatFile = (ExFatFile)usbFile;
//                        ExFatFile fatFile = (ExFatFile) fs.getRootDirectory();
//                        fatFile.testWrite(ExFatUtil.clusterToOffset(exFatFile.getfileCluster()));
//                        Toast.makeText(this,"写入成功",Toast.LENGTH_LONG).show();
//
//                    }
//                }*/
//
//              //  UsbFile file = fs.getRootDirectory();
//            //    UsbFile afile = file.
//                   //     createFile("a.txt");
//            //    afile.write(0,buffer);
//
//            }catch (IOException e){
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
//                    }
//                });
//            }

        }else if (var1 == buttonPanel2){
            if (Sample_text.getText().length() <= 0){
                logShow("请输入字符再写入");
                return;
            }
            try {
//                UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
//                if (storageDevices.length <= 0){
//                   // logShow("当前usb设备为空");
//                }
//                for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
//                    // 申请USB权限
//                    if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
//                        mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                     //   Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
//                        break;
//                    }
//                    // 初始化
//                    storageDevice.init();
                    // 获取分区
                    List<Partition> partitions = this.storageDevice.getPartitions();
                    if (partitions.size() == 0) {
//                        logShow("错误: 读取分区失败");
                        return;
                    }
                    // 仅使用第一分区
                    FileSystem fileSystem = partitions.get(0).getFileSystem();
//                    logShow("Volume Label: " + fileSystem.getVolumeLabel());
//                    logShow("Capacity: " + fSize(fileSystem.getCapacity()));
//                    logShow("Occupied Space: " + fSize(fileSystem.getOccupiedSpace()));
//                    logShow("Free Space: " + fSize(fileSystem.getFreeSpace()));
//                    logShow("Chunk size: " + fSize(fileSystem.getChunkSize()));

                    UsbFile root = fileSystem.getRootDirectory();
                    UsbFile[] files = root.listFiles();
                    UsbFile newFile = null;
                    for (UsbFile file : files)
                    //    logShow("文件: " + file.getName());
                        if(file.getName().contentEquals("a.txt")){
                            file.delete();
                        }

                    // 新建文件
                    {
                    }
                    newFile = root.createFile( "a.txt");
                 //   logShow("新建文件: " + newFile.getName());

                    // 写文件
                    // OutputStream os = new UsbFileOutputStream(newFile);
                    OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
                    os.write(Sample_text.getText().toString().getBytes());
                    os.close();
                    logShow("写文件成功,字符" + Sample_text.getText() + " 写入到 " + newFile.getName());

//                    storageDevice.close();
//                }
            } catch (Exception e) {
                logShow("错误: " + e);
            }


        } else if (var1 == buttonPanel3) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 1);
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Toast.makeText(this,"相机捕捉到照片",Toast.LENGTH_LONG).show();

        int i = 0;
        if (resultCode == Activity.RESULT_OK){
           Bundle bundle = data.getExtras();
           Bitmap bitmap = (Bitmap) bundle.get("data");

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] imageInByte = stream.toByteArray();

            try {
//                UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
//                if (storageDevices.length <= 0){
//                  //  logShow("当前usb设备为空");
//                }
//                for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手机只有一个USB设备
//                    // 申请USB权限
//                    if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
//                        mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
//                      //  Toast.makeText(this,"没有权限",Toast.LENGTH_LONG).show();
//                        break;
//                    }
//                    // 初始化
//                    storageDevice.init();
                    // 获取分区
                    List<Partition> partitions = this.storageDevice.getPartitions();
                    if (partitions.size() == 0) {
                       // logShow("错误: 读取分区失败");
                        return;
                    }
                    // 仅使用第一分区
                    FileSystem fileSystem = partitions.get(0).getFileSystem();
//                    logShow("Volume Label: " + fileSystem.getVolumeLabel());
//                    logShow("Capacity: " + fSize(fileSystem.getCapacity()));
//                    logShow("Occupied Space: " + fSize(fileSystem.getOccupiedSpace()));
//                    logShow("Free Space: " + fSize(fileSystem.getFreeSpace()));
//                    logShow("Chunk size: " + fSize(fileSystem.getChunkSize()));

                    UsbFile root = fileSystem.getRootDirectory();
                    UsbFile[] files = root.listFiles();
                    UsbFile newFile = null;
                    for (UsbFile file : files)
                     //   logShow("文件: " + file.getName());

                    // 新建文件
                    {
                    }

                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");//获取当前时间，进一步转化为字符串
                    Date date =new Date();
                    String str = format.format(date);
                    str += ".jpg";

                    newFile = root.createFile(str);
                  //  logShow("新建文件: " + newFile.getName());

                    // 写文件
                    // OutputStream os = new UsbFileOutputStream(newFile);
                    OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
                    os.write(imageInByte);
                    os.close();

                    logShow("相片写入成功，文件名为: " + str + " 共 " + imageInByte.length + "字节");

//                    storageDevice.close();
//                }
            } catch (Exception e) {
                logShow("错误: " + e);
            }
//
//            try {
//            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");//获取当前时间，进一步转化为字符串
//            Date date =new Date();
//            String str = format.format(date);
//            str += ".jpg";
//
//            ExFatFile file = (ExFatFile)fs.getRootDirectory();
//            // file.createDirectory("abc");
//            ExFatFile  abctxtFile =   (ExFatFile) file.createFile(str,imageInByte.length);
//
//            ByteBuffer buffer = ByteBuffer.allocate(imageInByte.length);
//            buffer.order(ByteOrder.LITTLE_ENDIAN);
//            buffer.put(imageInByte);
//            buffer.clear();
//
//            abctxtFile.write(0,buffer);
//
//            Toast.makeText(this,"写入成功",Toast.LENGTH_LONG).show();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//                Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
//            }
        }



    }
    /**
     * A native method that is implemented by the 'testexfatwrite' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}